"""
     base 是sqlalchemy基础类提供丰富的方法并继承属性。
    :copyright: © 2021 by the wtrees.松阳.
    :license: MIT, see LICENSE for more details.
"""
from sqlalchemy import Column, DateTime, func

from app.serve.wtrees.db import MixinJSONSerializer, db

# 基础的Basemodel
from app.util.page import Page


class BaseModel(db.Model, MixinJSONSerializer):
    __abstract__ = True
    create_time = Column(DateTime(timezone=True), server_default=func.now())
    update_time = Column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    delete_time = Column(DateTime(timezone=True))



    def set_attrs(self, attrs_dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key != "id":
                setattr(self, key, value)

    # 硬删除
    def delete(self, commit=False):
        db.session.delete(self)
        if commit:
            db.session.commit()

    # 查
    @classmethod
    def get(cls, start=None, count=None, one=True, **kwargs):
        if one:
            return cls.query.filter().filter_by(**kwargs).first()
        return cls.query.filter().filter_by(**kwargs).offset(start).limit(count).all()

    # 增
    @classmethod
    def create(cls, **kwargs):
        tmp = cls()
        for key in kwargs.keys():
            if hasattr(tmp, key):
                setattr(tmp, key, kwargs[key])
        db.session.add(tmp)
        if kwargs.get("commit") is True:
            db.session.commit()
        if kwargs.get("flush") is True:
            db.session.flush()
        return tmp

    def update(self, **kwargs):
        for key in kwargs.keys():
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
        db.session.add(self)
        if kwargs.get("commit") is True:
            db.session.commit()
        return self
